package com.lvcoding.clientfinal.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/index.html", "/test/**").permitAll()
                .anyRequest().authenticated()
                .and()
                // 开启客户端，会把yml中的oauth2配置的客户端全部加载
                .oauth2Client()
                .and()
                // 开启OAuth2登录
                .oauth2Login()      // (1)
                .successHandler((request, response, authentication) -> {
                    OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
                    String authorizedClientRegistrationId = token.getAuthorizedClientRegistrationId();
                    OAuth2User principal = token.getPrincipal();
                    if (authorizedClientRegistrationId.equalsIgnoreCase("github")) {
                        String username = principal.getAttribute("login");
                        String avatarUrl = principal.getAttribute("avatar_url");
                        log.info("Github登录成功，用户名：{}，头像：{}", username, avatarUrl);
                    } else if (authorizedClientRegistrationId.equalsIgnoreCase("gitee")) {
                        String username = principal.getAttribute("login");
                        String avatarUrl = principal.getAttribute("avatar_url");
                        log.info("Gitee登录成功，用户名：{}，头像：{}", username, avatarUrl);
                    }

                    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
                    // 授权成功后重定向到http://localhost:8000/user接口
                    redirectStrategy.sendRedirect(request, response, "/user");
                })
                .and()
                .logout()           // (2)
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true)
                .and()
                .csrf().disable();  // (3)
    }
}
